import { login, getUserInfo } from '@/api/user'
import { constantRoutes } from '@/router'
import { setToken, getToken, removeToken } from '@/utils/auth.js'

const state = {
  userInfo: {},
  token: getToken() || null, // 从本地存储中获取初始值
  routes: constantRoutes // 静态路由为初始值
}
const mutations = {
  setRoutes(state, newRoutes) {
    state.routes = [...constantRoutes, ...newRoutes]
  },
  setUserInfo(state, newUserInfo) {
    state.userInfo = newUserInfo
  },
  // state：当前模块的 state
  setToken(state, newToken) {
    state.token = newToken
    // 要将 token 存储到本地，持久化，保证下次刷新能够获取到 token 作为初始值
    setToken(newToken)
  },
  removeToken(state) {
    state.token = null
    removeToken()
  }
}
const actions = {
  async getUserInfo(ctx) {
    const userInfo = await getUserInfo()
    ctx.commit('setUserInfo', userInfo)
    return userInfo
  },
  // context 简写形式 ctx：当前模块的上下文 => 当前模块的 store 实例
  // reqData: { mobile, password }
  async login(ctx, reqData) {
    const token = await login(reqData)
    // 将 token 拿到， 然后调用 mutation 设置到 state 中
    ctx.commit('setToken', token)
    return token
  },
  logout(ctx) {
    ctx.commit('removeToken')
    ctx.commit('setUserInfo', {})
  }
}
const getters = {}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
